package com.product.magina.wechatserver.controller;

import com.google.common.collect.Maps;
import com.magina.common.exception.BusinessException;
import com.magina.common.response.Response;
import com.product.magina.wechatserver.entity.WeiXinUser;
import com.product.magina.wechatserver.model.PlanCustomerModel;
import com.product.magina.wechatserver.model.TextMessage;
import com.product.magina.wechatserver.service.WechatService;
import com.product.magina.wechatserver.utils.Decript;
import com.product.magina.wechatserver.utils.WeiXinUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "Wechat")
@Slf4j
public class WechatDataController {

    @Autowired
    private WechatService wechatService;

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping(value = "/testData")
    public String testInfo(HttpServletRequest request) throws Exception {
        log.info(request.getRemoteAddr());;
        log.info(this.getClass()+"测试通过了啊");
        return this.getClass().getName()+"测试通过了啊";
    }

    //    token
    @Value(value = "${wechat.projecttoken}")
    private String token;

    @Value(value="${wechat.projectappid}")
    private String projectAppId;

    @Value("${wechat.projectappsecret}")
    private String projectAppsecret;


    @RequestMapping(value = "/checkSignature")
    public void testInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("=============================进入Wechat==================================");
        log.info(request.toString());
        System.out.println("开始签名校验");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        //排序
        String sortString = sort(token, timestamp, nonce);
        //加密
        String mytoken = Decript.SHA1(sortString);

        //校验签名
        if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
            System.out.println("签名校验通过。");
            response.getWriter().print(echostr); //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
//            new Thread(){
//                public void run(){
//                    String getAccessTokenUrl = ProjectConst.ACCESS_TOKEN_URL.replace("APPID" ,projectAppId).replace("APPSECRET",projectAppsecret);
//                    Map<String,Object> getAccessTokenResult = restTemplate.getForObject(getAccessTokenUrl, Map.class);
//                    String accessToken = getAccessTokenResult.get("access_token").toString();
//                    String createMenuUrl = ProjectConst.CREATE_MENU_URL.replace("ACCESS_TOKEN" ,accessToken);
//                    Map<String, Object> jsonObject = restTemplate.postForObject(createMenuUrl, ProjectConst.INIT_MENU, Map.class);
//                    log.info(jsonObject.toString());
//                    log.info("init_menu return result:" + jsonObject);
//                    String errcode = jsonObject.get("errcode").toString();
//                    if("0".equals(errcode)){
//                        log.info("init_menu success!");
//                    }else {
//                        log.info("init_menu fail!");
//                    }
//                }
//            }.start();
        }
        testPostData(request);
    }

    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);

        StringBuilder sbuilder = new StringBuilder();
        for (String str : strArray) {
            sbuilder.append(str);
        }
        return sbuilder.toString();
    }

    @GetMapping("/tologin/userinfo")
    @ApiOperation(value = "传入code登录微信接口", notes = "前端传入code,调微信接口,获取微信用户信息,返回值:status为true则是此微信号绑定过,返回planList计划列表.status为flase" +
            "微信号尚未绑定手机号码,需要跳转手机验证码页面")
    public Response check(HttpServletRequest request, HttpSession session, Map<String, Object> map) throws BusinessException {
        log.info("=======================进入tologin/userinfo");
        //首先判断一下session中，是否有保存着的当前用户的信息，有的话，就不需要进行重复请求信息
        WeiXinUser weiXinUser = null;
        if (session.getAttribute("currentUser") != null) {
            weiXinUser = (WeiXinUser) session.getAttribute("currentUser");
        } else {
            /**
             * 进行获取openId，必须的一个参数，这个是当进行了授权页面的时候，再重定向了我们自己的一个页面的时候，
             * 会在request页面中，新增这个字段信息，要结合这个ProjectConst.Get_WEIXINPAGE_Code这个常量思考
             */
            String code = request.getParameter("code");
            try {
                //得到当前用户的信息(具体信息就看weixinUser这个javabean)
                weiXinUser = getTheCode(session, code);
                //将获取到的用户信息，放入到session中
                if(!ObjectUtils.isEmpty(weiXinUser) && !StringUtils.isEmpty(weiXinUser.getOpenId())){
                    session.setAttribute("currentUser", weiXinUser);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(ObjectUtils.isEmpty(weiXinUser)){
            return Response.fail("3999","查找微信用户失败!");
        }

        PlanCustomerModel model = wechatService.getPlanListByOpenId(weiXinUser.getOpenId());
        if(!model.getFlag()){
            map.put("status",false);
        }else{
            map.put("status",true);
            map.put("planList",model.getDsmtDistributionPlanList());
        }
        map.put("customer",model.getDsmtCustomer());
        map.put("weixinUser", weiXinUser);
        return Response.succeed(map);
    }

//    @Autowired
//    private DsmtCustomerDao dsmtCustomerDao;
    /**
     * 获取用户的openId
     *
     * @param session
     * @param code
     * @return 返回封装的微信用户的对象
     */
    private WeiXinUser getTheCode(HttpSession session, String code) throws BusinessException {
        Map<String, String> authInfo = new HashMap<>();
        Map result = Maps.newConcurrentMap();
        String openId = "";
        log.info("code:" + code);
        if (code != null) {
            // 调用根据用户的code得到需要的授权信息
            authInfo = wechatService.getAuthInfo(code);
            //获取到openId
            openId = authInfo.get("Openid");
            log.info("openId:" + openId);
        }
        // 获取基础刷新的接口访问凭证（目前还没明白为什么用authInfo.get("AccessToken");这里面的access_token就不行）
        String accessToken = WeiXinUtils.getAccessToken(projectAppId,projectAppsecret).getAccess_token();
        //获取到微信用户的信息
        WeiXinUser userinfo = wechatService.getUserInfo(accessToken, openId);
        return userinfo;
    }

    @PostMapping("/testPostData")
    public String testPostData(HttpServletRequest request) {
        String respMessage = null;
        log.info("enter testPostData method!");
        try {

            // xml请求解析
//            Map<String, String> requestMap = MessageUtil.xmlToMap(request);
            Map<String, String> requestMap = Maps.newConcurrentMap();

            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 消息内容
            String content = requestMap.get("Content");

            log.info("---------------FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType + content);

            // 文本消息
            if ("text".equals("text")) {
                //这里根据关键字执行相应的逻辑，只有你想不到的，没有做不到的
//                PicturePool pp = wechatResourceService.selectPictureWechat(content);
//                MoviePool mp = wechatResourceService.selectMovieWechat(content);
//                if (pp != null) {
//                    //自动回复图片
//                    ImgMessage imgMessage = new ImgMessage();
//                    WechatPicture wechatPicture = wechatResourceService.getPicture(pp.getId());
//                    Image image = new Image();
//                    image.setMediaId(wechatPicture.getMedia_id());
//                    imgMessage.setImage(image);
//                    imgMessage.setToUserName(fromUserName);
//                    imgMessage.setFromUserName(toUserName);
//                    imgMessage.setCreateTime(new Date().getTime());
//                    imgMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_IMAGE);
//                    respMessage = MessageUtil.imgMessageToXml(imgMessage);
//                } else
                    if ("1" != null) {
                    //自动回复
                    TextMessage text = new TextMessage();
//                    text.setContent(mp.getAddress());
                    text.setContent("www.baidu.com");
                    text.setToUserName(fromUserName);
                    text.setFromUserName(toUserName);
                    text.setCreateTime(new Date().getTime());
                    text.setMsgType(msgType);
//                    respMessage = MessageUtil.buildTextMessage(text);
                } else {
                    TextMessage text = new TextMessage();
                    text.setContent("亲，关键词匹配不上呢，请检查一下是否有同音字吧~\n" +
                            "回复“美女”“男神”“海报”“搞笑”等命令，可以获得相对应的精美图片。\n" +
                            "回复“电影”或者您想看的电影名称，即可得到在线观看的网址或云盘资源的链接。\n");
                    text.setToUserName(fromUserName);
                    text.setFromUserName(toUserName);
                    text.setCreateTime(new Date().getTime());
                    text.setMsgType(msgType);
//                    respMessage = MessageUtil.buildTextMessage(text);
                }
            }
//            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 事件推送
//                String eventType = requestMap.get("Event");// 事件类型
//
//                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 订阅
//                    TextMessage text = new TextMessage();
//                    text.setContent("客官，您来啦~\n" +
//                            "\n" +
//                            "回复“美女”“男神”“海报”“搞笑”等命令，可以获得相对应的精美图片。\n" +
//                            "回复“电影”或者您想看的电影名称，即可得到在线观看的网址或云盘资源的链接。\n" +
//                            "小编今日推荐：\n" +
//                            "菊豆\n" +
//                            "色戒\n" +
//                            "春光乍泄\n" +
//                            "苹果\n" +
//                            "生于妓院\n" +
//                            "（直接回复电影名称即可）");
//                    text.setToUserName(fromUserName);
//                    text.setFromUserName(toUserName);
//                    text.setCreateTime(new Date().getTime());
//                    text.setMsgType(msgType);
//                    respMessage = MessageUtil.textMessageToXml(text);
//                } else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {// 自定义菜单点击事件
//                    String eventKey = requestMap.get("EventKey");// 事件KEY值，与创建自定义菜单时指定的KEY值对应
//                    log.info("eventKey is:" + eventKey);
//                    if (eventKey.equals("zhaodianying")) {
//                        TextMessage text = new TextMessage();
//                        text.setContent("回复“电影” 或 直接回复电影名称，小编就会很快回复您观看网址噢。\n" +
//                                "回复“美女”“男神”“海报”“搞笑”等命令，可以获得相对应类型的精美图片。\n" +
//                                "您还可以添加客服微信：girlnevercryy进入“逗芽电影福利红包群”，各种福利，任性红包满天飞~~~");
//                        text.setToUserName(fromUserName);
//                        text.setFromUserName(toUserName);
//                        text.setCreateTime(new Date().getTime());
//                        text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
//                        respMessage = MessageUtil.textMessageToXml(text);
//                    }
//                    if (eventKey.equals("qiuziyuan")) {
//                        TextMessage text = new TextMessage();
//                        text.setContent("如果亲没有找到自己中意的电影资源，请添加客服微信：jfwx-hrd 把想要的电影资源名称留言给小编，小编就会立刻马不停蹄的免费去帮您找噢~\n");
//                        text.setToUserName(fromUserName);
//                        text.setFromUserName(toUserName);
//                        text.setCreateTime(new Date().getTime());
//                        text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
//                        respMessage = MessageUtil.textMessageToXml(text);
//                    }
//                }
//            }
        } catch (Exception e) {
            log.error("error......");
            e.printStackTrace();
        }
        return respMessage;
    }


}
